//
//  shopuserMoneyViewController.m
//  EasyToTesco
//
//  Created by mc on 16/3/11.
//  Copyright © 2016年 Jack. All rights reserved.
//

#import "shopuserMoneyViewController.h"

#import "AFNetworking.h"
#import "ReadLoginData.h"
#import "FirstTableViewCell.h"
#import "SecondTableViewCell.h"
#import "ThiredTableViewCell.h"
#import "SectionView.h"

#define WEIGHT [UIScreen mainScreen].bounds.size.width
#define HEIGHT [UIScreen mainScreen].bounds.size.height
@interface shopuserMoneyViewController () <UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate,UIAlertViewDelegate>

@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic,copy) NSString *userName;
@property (nonatomic,strong) UITextField *numKeyBoard;
@property (nonatomic,strong) UIButton *didClickButton;

/**
 *  用户信息字段
 */
@property (nonatomic,strong) NSMutableDictionary *userNameArray;

/**
 *  cell数据数组
 */
@property (nonatomic,strong)NSMutableDictionary *userData;

/**
 *  上传金额字段
 */
@property (nonatomic,assign)NSInteger JinE;

/**
 *  营业账户余额
 */
@property (nonatomic,copy)NSString *yyye;
@end

@implementation shopuserMoneyViewController

- (NSMutableDictionary *)userData {
    if (!_userData) {
        _userData = [NSMutableDictionary dictionary];
    }
    return _userData;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self addshopmoneytopviewUI];
    
    
    NSDictionary *dic = [ReadLoginData readLoginData];
    self.userName =[dic[@"data"] objectForKey:@"username"];

    self.yyye = [dic[@"data"] objectForKey:@"yyye"];
    NSDictionary *param = @{@"username":self.userName};
    [self loadUserData:param];
    
    [self.view addSubview:self.tableView];
    [self loadUserData:param];
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0,self.secondView.frame.size.height + 10, WEIGHT, HEIGHT) style:UITableViewStyleGrouped];
    
    self.tableView.contentInset = UIEdgeInsetsMake(-1, 0, 0, 0);
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    [self.view addSubview:self.tableView];
    
    
}


- (void)addshopmoneytopviewUI {
    
    UIImageView *image1 = [[UIImageView alloc] initWithFrame:CGRectMake(10, (self.secondView.frame.size.height-30)/2, 20, 20)];
    image1.image = [UIImage imageNamed:@"goback-icon.png"];
    [self.secondView addSubview:image1];
    self.leftBtn.hidden = YES;
    
    UIButton *goBackBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    goBackBtn.frame = CGRectMake(0, 0, self.secondView.frame.size.height, self.secondView.frame.size.height);
    [goBackBtn addTarget:self action:@selector(gobackClick) forControlEvents:UIControlEventTouchUpInside];
    [self.secondView addSubview:goBackBtn];
    self.titleLabel.text = @"营业额结算";

}

- (void)gobackClick {
    [self dismissViewControllerAnimated:YES completion:nil];
}



#pragma 接口
- (void)loadUserData:(NSDictionary *)dict {
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [manager POST:@"http://www.ylgw8.com/AppUser/UserInfo" parameters:dict success:^(NSURLSessionDataTask *task, id responseObject) {
        
        self.userData = [self toArrayOrNSDictionary:responseObject];
        
        NSLog(@"%@",self.userData);
        
        [self.tableView reloadData];
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
    }];
}


// 将JSON串转化为字典或者数组
- (id)toArrayOrNSDictionary:(NSData *)jsonData{
    NSError *error = nil;
    id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData
                                                    options:NSJSONReadingAllowFragments
                                                      error:&error];
    
    if (jsonObject != nil && error == nil){
        return jsonObject;
    }else{
        // 解析错误
        return nil;
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma MARK dataSourse
- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
    return 4;
}

- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0 ) {
        return 1;
    } else if (section == 1) {
        return 2;
        
    } else if (section == 2) {
        return 3;
    } else {
        return 1;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        FirstTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"FirstCell"];
        
        if (cell == nil) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"FirstTableViewCell" owner:nil options:nil] lastObject];
            
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        
        return cell;
    } else if (indexPath.section == 1) {
        static NSString *second = @"SecondCell";
        SecondTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:second];
        
        if (cell == nil) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"SecondTableViewCell" owner:nil options:nil] lastObject];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        
        if (indexPath.row == 0) {
            cell.name.text = @"银   行:";
            
            cell.answer.text = [self loadBANKWeithNum: [[self.userData[@"data"] objectForKey:@"yinhang"]integerValue]];
        } else {
            cell.hiddenLabel.hidden = NO;
            cell.name.text = @"真实姓名:";
            cell.answer.text = [self.userData[@"data"] objectForKey:@"xingming"];
//            cell.answer.text = @"吴天明 ";
        }
        
        return cell;
    } else if (indexPath.section == 2){
        SecondTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SecondCell"];
        if (cell == nil) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"SecondTableViewCell" owner:nil options:nil] lastObject];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        
        if (indexPath.row == 0) {
            cell.name.text = @"开户行:";
            cell.answer.text = [self.userData[@"data"] objectForKey:@"kaihuhang"];
        } else if (indexPath.row == 1) {
            cell.name.text = @"尾   号:";
            cell.answer.text = [NSString stringWithFormat:@"**** %@",[self loadBankLastFourNum:[self.userData[@"data"] objectForKey:@"zhanghao"]]];
        } else {
            cell.name.text = @"营业账户余额:";
            cell.answer.text = self.yyye;
        }
        
        return cell;
    } else {
        ThiredTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ThiredTableViewCell"];
        
        if (cell == nil) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"ThiredTableViewCell" owner:nil options:nil] lastObject];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        cell.QingShuRuJine.delegate = self;
        [cell.QingShuRuJine addTarget:self action:@selector(textFieldDidInPutEnd:) forControlEvents:UIControlEventEditingDidEnd];
        self.numKeyBoard = cell.QingShuRuJine;
        
        
        return cell;
    }
    
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
   
    if (section == 3) {
//        tableView.userInteractionEnabled = YES;
        return [self loadFooterView];
    }
    return nil;
}

//- (nullable UITableViewHeaderFooterView *)footerViewForSection:(NSInteger)section {
//    if (section == 3) {
//        return [self loadFooterView];
//    }
//    return nil;
//}

- (NSString *)loadBankLastFourNum:(NSString *)string {
    
    NSLog(@"%@",string);
    NSInteger length = [string length];
    
    NSString *lastString = [string substringWithRange:NSMakeRange(length - 4, 4)];
    NSLog(@"%@",lastString);
    
    return lastString;
    
}

- (NSString *)loadBANKWeithNum:(NSInteger)BankNum {
    switch (BankNum) {
        case 1:
            return @"中国农业银行";
            break;
            
        case 2:
            return @"中国工商银行";
            break;
            
        case 3:
            return @"中国建设银行";
            break;
            
        case 4:
            return @"中国银行";
            break;
            
        case 5:
            return @"交通银行"; 
            break;
            
        case 6:
            return @"招商银行";
            break;
            
        case 7:
            return @"中国民生银行";
            
        default:
            break;
    }
    return @"请确认开户银行";
}

- (void)textFieldDidInPutEnd:(UITextField *)textField{
    NSInteger JinE = textField.text.integerValue;
    self.JinE = JinE;
#warning 金额
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    
    if (section == 3) {
        return 65;
    }
    return 20;
}


- (UIView *)loadFooterView{
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(58, 28, WEIGHT - 58 * 2, 30)];
    [button setTitle:@"立即支付" forState:UIControlStateNormal];
    [button setBackgroundColor:[UIColor blueColor]];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(buttonDidClick) forControlEvents:UIControlEventTouchUpInside];
    self.didClickButton = button;
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WEIGHT, 65)];

    [footerView addSubview:button];
    
    return footerView;
}

//- (UITableViewHeaderFooterView)
- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView {
    [self.numKeyBoard resignFirstResponder];
}

- (void)textFieldDidBeginEditing:(UITextField *)textField {
    [self.numKeyBoard becomeFirstResponder];
}

#pragma 立即支付button点击事件
- (void)buttonDidClick {
    
    NSLog(@"%@",self.userName);
    NSLog(@"%ld",(long)self.JinE);
    
    if (self.JinE == 0) {
        UIAlertView *alview = [[UIAlertView alloc] initWithTitle:@"提示" message:@"您尚未输入金额,请输入金额" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alview show];
    } else {
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        NSString *jine = [NSString stringWithFormat:@"%ld",self.JinE];
        NSDictionary *param = @{@"username":self.userName,@"jine":jine};
//        NSDictionary *param = @{@"username":@18000000000,@"jine":@200};
        [manager POST:@"http://www.ylgw8.com/AppHz/Jies" parameters:param success:^(NSURLSessionDataTask *task, id responseObject) {
            
            UIAlertView *alview = [[UIAlertView alloc] initWithTitle:nil message:[NSString stringWithFormat:@"%@",[self toArrayOrNSDictionary:responseObject][@"message"]] delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alview show];
            
            
            
        } failure:^(NSURLSessionDataTask *task, NSError *error) {
            
        }];

        
    }
}

#pragma UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex {
    
    NSLog(@"%s",__func__);
    
    [self clearAlertView];
}

- (void)clearAlertView{
    self.numKeyBoard.text = @"";
}



@end
